import axios from 'axios'
import { useAuthStore } from '../stores/auth'

const API_URL = 'http://localhost:8000'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  withCredentials: true // 确保跨域请求发送cookies
})

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    const authStore = useAuthStore()
    if (authStore.token) {
      config.headers['Authorization'] = `Bearer ${authStore.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  response => response,
  error => {
    const authStore = useAuthStore()
    
    // 如果响应是401 Unauthorized，则登出用户
    if (error.response && error.response.status === 401) {
      authStore.logout()
    }
    
    return Promise.reject(error)
  }
)

export default {
  // 服务器相关API
  servers: {
    getAll() {
      return apiClient.get('/api/servers/')
    },
    
    getById(id: string) {
      return apiClient.get(`/api/servers/${id}/`)
    },
    
    getByCategory(categoryName: string) {
      return apiClient.get(`/api/servers/?category_name=${encodeURIComponent(categoryName)}`)
    },
    
    getMyServers() {
      return apiClient.get('/api/user-servers/?owner=me')
    },
    
    create(serverData: any) {
      return apiClient.post('/api/user-servers/', serverData)
    },
    
    update(id: string, serverData: any) {
      return apiClient.put(`/api/user-servers/${id}/`, serverData)
    },
    
    delete(id: string) {
      return apiClient.delete(`/api/user-servers/${id}/`)
    },

    // 获取服务器分类
    getCategories() {
      return apiClient.get('/api/categories/')
    },

    // 获取所有标签
    getTags() {
      return apiClient.get('/api/tags/')
    }
  },
  
  // 用户相关API
  users: {
    getCurrent() {
      return apiClient.get('/api/users/me/')
    }
  }
} 